/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.start.model;

import business.service.MongoDbFactory;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.star.common.UserData;
import com.star.common.UserGroupData;
import com.star.common.UserType;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import org.apache.log4j.Logger;
import org.bson.types.ObjectId;

/**
 *
 * @author Administrator
 */
public class UserGroupModel {
    private static final String GROUP_USER_COLLECTION = "user_group";
    private static UserGroupModel instance = null;
    private static final Lock iLock = new ReentrantLock();
    protected final Logger logger = Logger.getLogger(this.getClass());
    private static final DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
    
    public static UserGroupModel getInstance() {
        iLock.lock();
        try {
            if (instance == null) {
                instance = new UserGroupModel();
            }            
        } finally {
            iLock.unlock();
        }
        return instance;
    }

    public UserGroupModel() {
        try {
        } catch (Exception e) {
            logger.error("UserGroupModel.constructor: " + e.getMessage());
        }
    }
    
    
    public UserGroupData getUserGroupById(String id) {
        try {
            BasicDBObject basicDBObject = new BasicDBObject("_id", new ObjectId(id));
            DB db = MongoDbFactory.getConnection();
            DBCollection coll = db.getCollection(GROUP_USER_COLLECTION);
            DBCursor cursor = coll.find(basicDBObject);
            if (cursor.hasNext()) {
                DBObject dbObject = cursor.next();
                String groupName = (String) dbObject.get("groupname");
                String groupRole = (String) dbObject.get("grouprole");   
                long created = (long) dbObject.get("created");
                UserGroupData userGroupData = new UserGroupData(id, groupName, groupRole, created);                

                return userGroupData;
            }
        } catch (Exception ex) {
            logger.error("UserGroupModel.getUserGroupById: " + ex.getMessage(), ex);
        }
        return null;
    }
    
    
    public UserGroupData getUserGroupByName(String userGroupName) {
        try {
            BasicDBObject basicDBObject = new BasicDBObject("groupname", userGroupName);
            DB db = MongoDbFactory.getConnection();
            DBCollection coll = db.getCollection(GROUP_USER_COLLECTION);
            DBCursor cursor = coll.find(basicDBObject);
            if (cursor.hasNext()) {                
                DBObject dbObject = cursor.next();
                String id = ((ObjectId) dbObject.get("_id")).toString();
                String groupName = (String) dbObject.get("groupname");
                String groupRole = (String) dbObject.get("grouprole");   
                long created = (long) dbObject.get("created");
                UserGroupData userGroupData = new UserGroupData(id, groupName, groupRole, created); 
                return userGroupData;                
            }
        } catch (Exception ex) {
            logger.error("UserGroupModel.getUserGroupByName: " + ex.getMessage(), ex);
        }
        return null;
    }
    
    
    public List<UserGroupData> getUserGroup(int start, int limit) {
        List<UserGroupData> lstUserGroup = null;
        try {
            BasicDBObject basicDBObject = new BasicDBObject("_id", -1);
            DB db = MongoDbFactory.getConnection();
            DBCollection coll = db.getCollection(GROUP_USER_COLLECTION);
            DBCursor cursor = coll.find().sort(basicDBObject);
            if (limit != -1) {
                cursor = cursor.skip(start).limit(limit);
            }
            lstUserGroup = new ArrayList<>();
            while (cursor.hasNext()) {
                DBObject dbObject = cursor.next();
                String id = ((ObjectId) dbObject.get("_id")).toString();
                String groupName = (String) dbObject.get("groupname");
                String groupRole = (String) dbObject.get("grouprole");   
                long created = (long) dbObject.get("created");
                UserGroupData userGroupData = new UserGroupData(id, groupName, groupRole, created); 
                lstUserGroup.add(userGroupData);
            }
        } catch (Exception ex) {
            logger.error("UserGroupModel.getUserGroup: " + ex.getMessage(), ex);
        }
        return lstUserGroup;
    }
    
    //
    public List<String> getGroupRole(String id) {
        List<String> lstRole = null;
        try {
            BasicDBObject basicDBObject = new BasicDBObject("_id", new ObjectId(id));
            DB db = MongoDbFactory.getConnection();
            DBCollection coll = db.getCollection(GROUP_USER_COLLECTION);
            DBCursor cursor = coll.find(basicDBObject);
            if (cursor.hasNext()) {
                DBObject dbObject = cursor.next();
                String groupRole = (String) dbObject.get("grouprole");   
                lstRole = new ArrayList<>();
                if (groupRole != null && !groupRole.equalsIgnoreCase("")) {
                    lstRole.addAll(Arrays.asList(groupRole.split("\\s*,\\s*")));
                }
            }
        } catch (Exception e) {
            logger.error("UserGroupModel.getGroupRole: " + e.getMessage(), e);
        }
        return lstRole;
    }
    //end
    
    //
    public String addUserGroup(UserGroupData userGroupData) {
        String id = "";
        try {
            BasicDBObject basicDBObject = new BasicDBObject()
                    .append("groupname", userGroupData.getGroupName())
                    .append("grouprole", userGroupData.getGroupRole())                    
                    .append("created", userGroupData.getCreated());

            DB db = MongoDbFactory.getConnection();
            DBCollection coll = db.getCollection(GROUP_USER_COLLECTION);
            coll.insert(basicDBObject);

            ObjectId objectId = (ObjectId) basicDBObject.get("_id");
            id = objectId.toString();
        } catch (Exception ex) {
            logger.error("UserGroupModel.addUserGroup: " + ex.getMessage());
        }
        return id;
    }
    
    
    public boolean updateUserGroup(UserGroupData userGroupData) {
        try {
            BasicDBObject basicDBObject = new BasicDBObject()
                    .append("groupname", userGroupData.getGroupName())
                    .append("grouprole", userGroupData.getGroupRole());
            
            DB db = MongoDbFactory.getConnection();
            DBCollection coll = db.getCollection(GROUP_USER_COLLECTION);

            BasicDBObject updateDBObject = new BasicDBObject("$set", basicDBObject);
            BasicDBObject searchDBQuery = new BasicDBObject("_id", new ObjectId(userGroupData.getId()));
            coll.update(searchDBQuery, updateDBObject);
            return true;
        } catch (Exception ex) {
            logger.error("UserGroupModel.updateUserGroup: " + ex.getMessage());
        }
        return false;
    }
    
    
    public boolean updateGroupRole(String id, String groupRole) {
        try {
            BasicDBObject basicDBObject = new BasicDBObject()
                .append("grouprole", groupRole);

            DB db = MongoDbFactory.getConnection();
            DBCollection coll = db.getCollection(GROUP_USER_COLLECTION);

            BasicDBObject updateDBObject = new BasicDBObject("$set", basicDBObject);
            BasicDBObject searchDBQuery = new BasicDBObject("_id", new ObjectId(id));
            coll.update(searchDBQuery, updateDBObject);
            return true;
        } catch (Exception ex) {
            logger.error("UserGroupModel.updateGroupRole: " + ex.getMessage());
        }
        return false;
    }
    
    
    public boolean deleteUserGroup(String id) {
        try {
            DB db = MongoDbFactory.getConnection();
            DBCollection coll = db.getCollection(GROUP_USER_COLLECTION);
            coll.remove(new BasicDBObject("_id", new ObjectId(id)));

            return true;
        } catch (Exception ex) {
            logger.error("UserGroupModel.deleteUserGroup: " + ex.getMessage(), ex);
        }
        return false;
    }
}
